<?php


namespace app\admin\controller\admin;


use app\common\controller\Backstage;
use thans\jwt\facade\JWTAuth;
use think\captcha\facade\Captcha;

use think\facade\Cookie;
use think\facade\Session;
use think\facade\View;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("前台用户相关,登录相关")
 */
class User extends Backstage
{

    //中间件不验证的方法
    protected $middleware = [
        'app\\middleware\\Admin' => [
            'except' => [
                'getCaptcha', 'apiLogin'
            ]
        ]
    ];

    /**
     * @Apidoc\Title("接口登录接口")
     * @Apidoc\Url("/admin/admin.User/apiLogin")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("account", type="string", require=true, desc="账号")
     * @Apidoc\Param("password", type="string", require=true, desc="密码")
     * @Apidoc\Param("captcha", type="string", require=true, desc="验证码")
     * @Apidoc\Returned("data", type="array", desc="返回说明")
     */
    public function apiLogin()
    {
        $post = $this->request->param();
        try {
            $this->Validate($post, [
                'account|账号' => 'require',
                'password|密码' => 'require',
                'captcha|验证码' => 'require|length:4'
            ]);
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }

        $adminCaptcha = session('adminCaptcha');
        if ($adminCaptcha != strtolower($post['captcha']) && env('APP_DEBUG') != 1) {
            return $this->ajax(0, '验证码错误');
        }

        $info = new \app\common\model\Admin();

        $user = $info->where([
            'account' => $post['account']
        ])->find();

        if (empty($user)) {
            return $this->ajax(0, '账号不存在');
        }
        $user = $user->toArray();
        //超级管理员密码 a772c24186e09f71809f05020fd7e320(admin2021)账号(admin)
        $password = md5(md5($post['password']) . "admin");

        if ($password != $user['password']) {
            $info->update([
                'lately_time' => time(),
                'lately_ip' => $this->request->ip(),
                'error_number' => ['inc', 1],
            ], ['id' => $user['id']]);
            return $this->ajax(0, '密码错误');
        }

        if ($user['status'] == 2) {
            return $this->ajax(0, '账号已被冻结');
        }
        $info->update([
            'lately_time' => time(),
            'lately_ip' => $this->request->ip()
        ], ['id' => $user['id']]);

        unset($user['password']);
        session('admin', $user);
        $token = JWTAuth::builder([
            'admin_id' => $user['id'],
            'type' => 'admin',
        ]);//参数为用户认证的信息，请自行添加
        return $this->ajax(1, "登陆成功", [
            'token' => 'bearer ' . $token
        ]);
    }

    /**
     * @Apidoc\Title("密码修改")
     * @Apidoc\Url("/admin/admin.User/editPassword")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("password", type="string", require=true, desc="密码")
     * @Apidoc\Param("password_confirm", type="string", require=true, desc="确认密码")
     * @Apidoc\Returned("data", type="array", desc="返回说明")
     */
    public function editPassword()
    {
        if (!\app\common\service\RedisQuantity::FrequencyLimit(md5(request()->controller() . request()->action() . $wx_info_id), 2)) {
            throw new \Exception('请求频繁,稍后再试');
        }
        $post = $this->request->param();
        try {
            $this->Validate($post, [
                'password|密码' => 'require|confirm|length:6,25'
            ]);
            $result = JWTAuth::auth();//token验证
            $admin_id = $result['admin_id'];

            $info = new \app\common\model\Admin();

            $info->where([
                'id' => $admin_id
            ])->update([
                'password' => md5(md5($post['password']) . "admin")
            ]);
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getError());
        }
        return $this->ajax(1, "修改成功");
    }

    /**
     * @Apidoc\Title("验证码图片")
     * @Apidoc\Url("/admin/admin.User/getCaptcha")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("img", type="array", desc="验证码图片")
     */
    public function getCaptcha()
    {
        $val = Captcha::createApi();
        session('adminCaptcha', strtolower($val['val']));
        $root = $this->request->domain();
        return $this->ajax(1, "成功", [
            'img' => $root . $val['url']
        ]);
    }


    /**
     * @Apidoc\Title("退出登录")
     * @Apidoc\Url("/admin/User/logout")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("data", type="array", desc="说明")
     */
    public function logout()
    {
        session('admin', null);
        JWTAuth::refresh();
        return $this->ajax(1, "退出成功");
    }
}
